<template>
  <div class="login">
    <div class="title">欢迎登录</div>
    <van-form>
      <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名" size="large"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" size="large"
        :rules="[{ required: true, message: '请填写密码' }, { validator: validatePassword, message: '密码长度至少为6位' }]" />
      <div style="margin-top: 16px;">
        <van-button round block type="primary" @click="onSubmit">登录</van-button>
      </div>
      <div class="footer">
        <span>没有账号,</span>
        <span class="register" @click="goRegister">去注册</span>
      </div>
    </van-form>
  </div>
</template>
  
<script>
import { ref, getCurrentInstance, onMounted } from 'vue'
import router from '../router/index';
export default {
  // eslint-disable-next-line no-unused-vars
  setup(props, cxt) {
    const { proxy } = getCurrentInstance()
    const username = ref('');
    const password = ref('');
    let loginInfo;
    const validatePassword = (val) => /\d{6}/.test(val);

    const onSubmit = async () => {
      let data = { username: username.value, password: password.value }
      loginInfo = await proxy.$axios.post('/login', data)
      // console.log(loginInfo);

      if (username.value != loginInfo.username || password.value != loginInfo.password + '') {
        proxy.$toast.fail('用户名或密码错误...');
      } else {
        localStorage.setItem('isLogin', JSON.stringify(true))
        localStorage.setItem('user', username.value)
        proxy.$toast.success('登录成功')
        router.push('/home')
      }
    }

    const goRegister = () => {
      router.push('/register')
    }

    onMounted(() => {
    });


    return {
      username,
      password,
      validatePassword,
      onSubmit,
      goRegister
    };
  },
}
</script>
  
<style scoped>
.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f7f0f0;
  height: 100%;
}

.title {
  font-size: 1.75rem;
  color: #0f0707;
}

.van-form {
  height: 18.75rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.van-cell--large {
  margin: 0.625rem 0;
  border-radius: 0.5rem;
}

.footer {
  color: #0c0505;
  text-align: center;
  font-size: 0.875rem;
  padding: 0.625rem 0;
}

.register {
  color: #0e0404;
  font-weight: bold;
}
</style>